package com.gdpu.service.impl;

import com.gdpu.api.CommonPage;
import com.gdpu.dao.UmsAddressDao;
import com.gdpu.mapper.UmsAddressMapper;
import com.gdpu.model.UmsAddress;
import com.gdpu.model.UmsAddressExample;
import com.gdpu.service.UmsAddressService;
import com.gdpu.service.UmsMemberService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author:weiming
 * @Date:2021/6/7
 */
@Service
public class UmsAddressServiceImpl implements UmsAddressService {
    @Autowired
    private UmsAddressMapper umsAddressMapper;
    @Autowired
    private UmsAddressDao umsAddressDao;
    @Autowired
    private UmsMemberService umsMemberService;

    @Override
    public int setDefaultAddress() {
        int count;
        UmsAddress record = new UmsAddress();
        UmsAddressExample example = new UmsAddressExample();
        example.createCriteria().andUserIdEqualTo(umsMemberService.getCurrentMember().getId());
        record.setIsDefault(0);
        count =  umsAddressMapper.updateByExampleSelective(record, example);
        return count;
    }

    @Override
    public CommonPage getList(Integer pageNum, Integer pageSize) {
        Page page = PageHelper.startPage(pageNum,pageSize);
        UmsAddressExample example = new UmsAddressExample();
        example.createCriteria()
                .andUserIdEqualTo(umsMemberService.getCurrentMember().getId()).
                andIsDeletedEqualTo(0);

        List<UmsAddress> umsAddresses = umsAddressMapper.selectByExample(example);
        return CommonPage.restPage(umsAddresses, page);
    }
    @Override
    public UmsAddress get(Integer addressId) {

        UmsAddress umsAddress = umsAddressMapper.selectByPrimaryKey(addressId);

        return umsAddress;
    }

    @Override
    public int add(UmsAddress umsAddress) {
        int count;
        umsAddress.setIsDeleted(0);
        count = umsAddressMapper.insert(umsAddress);
        return count;
    }

    @Override
    public int update(UmsAddress umsAddress) {
        int count = 0;
        // 如果是设置成默认，需要把其他的默认更新成0
        UmsAddress address = umsAddressMapper.selectByPrimaryKey(umsAddress.getId());
        if (address.getIsDefault()==0 && umsAddress.getIsDefault() ==1){
            setDefaultAddress();
        }
        count = umsAddressMapper.updateByPrimaryKey(umsAddress);
        return count;
    }


}
